<?php

namespace app\common\model;

use app\api\service\WxPay;
use app\common\controller\Helper;
use think\facade\Log;
use think\Model;

class OauthCommission extends Model
{
    use Helper;

    protected $table = 'oauth_commission';

    const WITHDRAW_NO = 0;
    const WITHDRAW_SUCCESS = 1;
    const WITHDRAW_FAIL = 2;

    public static function attributes($attribute, $key = null)
    {
        $list = [
            'withdrawal_status' => [
                self::WITHDRAW_NO => '未提现',
                self::WITHDRAW_SUCCESS => '提现成功',
                self::WITHDRAW_FAIL => '提现失败',
            ],
        ];
        return self::attributeReturn($list, $attribute, $key);
    }

    /**
     * 企业转账给用户
     * @param $tradeNo
     * @param $openid
     * @param $amount
     * @param $desc
     * @return array
     * @throws \Exception
     */
    public static function transfers($tradeNo, $openid, $amount, $desc)
    {
        $wxPay = new WxPay();
        $param = [
            // 商户订单号
            'partner_trade_no' => $tradeNo,
            'openid' => $openid,
            'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名; FORCE_CHECK：强校验真实姓名
            'amount' => $amount * 100, // 单位为分
            'desc' => $desc,
        ];

        try {
            // 企业转账
            $return = $wxPay->transfers($param);
            if ($return['return_code'] == 'SUCCESS' && $return['result_code'] == 'SUCCESS') {
                return [
                    'success' => true,
                    'partner_trade_no' => $return['partner_trade_no'],
                ];
            } else {
                // 实时写入报错信息
                Log::write($return, 'wxPayTransfers');
                return [
                    'success' => false,
                    'err_code_des' => $return['err_code_des'],
                ];
            }
        } catch (\Exception $e) {
            Log::write($e->getMessage(), 'wxPayTransfersException');
            return [
                'success' => false,
                'err_code_des' => $e->getMessage(),
            ];
        }
    }
}